<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Loader;
use think\Db;
use think\Config;

use app\common\BaseController;
use app\model\UserModel;
use app\model\AppointmentModel;
use app\model\MeetingModel;
use app\model\CodeModel;

/**工具类**/
use app\common\Tool\ApiErrDesc;
use redis\Redis;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

class Code extends BaseController
{
    private $wechatOA;
    private $table_meeting_view = 'view_new_app_meeting_info';

    public function _initialize(){
        $this->redis = new Redis();
        $this->noNeedLogin = ['session_set','test','testcode','codelist','makecode_easy'];
        Loader::import('Wechat_OA', EXTEND_PATH);
        $this->wechatOA = new \Wechat_OA();
    }

    /**
     * 统一,扫码接口
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-02T10:10:49+0800
     * @LastTime     2020-09-02T10:10:49+0800
     * @return       [type]                   [description]
     * @remark
     */
    public function scancode(){
        $code = $this->request->param('icp_sn');
        $today = strtotime(date("Y-m-d"),time());
        $enddaytime = $today+60*60*24;
        $offset = trim($this->request->param('offset'))?:0;
        $length = trim($this->request->param('length'))?:999;
        if(!$code){return $this->jsonData(ApiErrDesc::UNKNOWN_ERR[0],ApiErrDesc::UNKNOWN_ERR[1]);}

        $type = substr($code, 0, 2); //订单号前两位扫码场景，ML--邀请码 UL--用户码

        switch ($type) {
            case 'ML':
               /**邀请码业务逻辑**/
               //$this->user['roleid']=6;
               if($code && ($this->user['roleid']==6 || $this->user['roleid'] ==5)){
                   $where = 'meeting_code = "'.$code.'"';
                   $res = $this->find('view_new_app_meeting_info',$where);
                   if(!$res){return toJson(['message'=>'见面信息不存在','code'=>400]);}
                   /**lasttime 2020年10月26日14:26:35
                    *以下需要判断 公司类型 在判断访问公司区域

                   **/
                   //if($res['companyid']!=$this->user['companyid']){return toJson(['message'=>'当前访问信息不在此区域','code'=>400]);}
                   
                   // $where = 'meeting_code = "'.$code.'" and companyid = '.$this->user['companyid'].' and appointment_status = 0 and arrive_status not in(4,5) and app_visittime between '.$today.' and '.$enddaytime;
                   $where = 'meeting_code = "'.$code.'"';
                   $order = 'app_visittime desc';
            
                   $data = $this->selectView($this->table_meeting_view, $where, $field = '*', $offset, $length, $order);
                   $count = $this->total($this->table_meeting_view, $where, $field = '*');
            
                   return toJson(['message'=>'Success_保安访客列表','code'=>200,'data'=>$data,'count'=>$count,'requestTime'=>time()]);
            
               }
               //受访人扫访客二维码码
               if($code){
                   $where = 'meeting_code = "'.$code.'"';
                   $res = $this->find('view_new_app_meeting_info',$where);
                   if(!$res){return toJson(['message'=>'见面信息不存在','code'=>400]);}
                   //检查状态
                   $check_status = [3,4,5,6];
                   if(in_array($res['arrive_status'], $check_status)){return toJson(['message'=>'已接待访客,无需重复确认','data'=>$res,'code'=>400]);}
                   //开始确认  更新状态
                   if($this->uid == $res['app_uid']){
                        $updata = [
                            'meettime'=>time(),
                            'status'=>3,
                        ];
                        if($res['arrivetime']==NULL){$updata['arrivetime']=time()-1;}
                        if($res['passtime']==NULL){$updata['passtime']=time()-1;}
                        $result = $this->update('arrive','id = '.$res['arrive_id'],$updata);
                        if($result){
                            $appointmentData = $res;
                            Loader::import('Wechat_OA', EXTEND_PATH);
                            //推送受访人和访客
                            $url ='http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=';
                            $url_data = [
                                'id' => $appointmentData['appointmentid'],
                            ];
                            //$appointmentData['id'] = $appointmentData['appointmentid'];
                            $urldata = json_encode($url_data);
                            $url = $url.$urldata;
                           
                            $wechatOA = new \Wechat_OA();
                            $nowtime = strtotime(date("Y-m-d H:i:s"),time());
                            //访客信息
                            $u_visterInfo = $this->find('view_user','id = '.$res['vister_uid']);

                            /*受访人*/
                            $data = ['title'=>'接待访客通知',
                                    'openid'=>$this->user->openid,
                                    'name'=>$u_visterInfo['name'],
                                    'mobile'=>$u_visterInfo['mobile'],
                                    'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
                                    'status'=>'成功接待访客',
                                    'remark'=>"",
                                    'url'=>$url
                            ];
                            $result = $wechatOA->send_message($data);
                            // 访客
                              $url ='http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=';
                              //$appointmentData['id'] = $appointmentData['appointmentid'];
                              $url_data = [
                                  'id' => $appointmentData['appointmentid'],
                              ];
                              $urldata = json_encode($url_data);
                              $url = $url.$urldata;
                              $data = ['title'=>'接待通知',
                                    'openid'=>$u_visterInfo['openid'],
                                    'name'=>$u_visterInfo['name'],
                                    'mobile'=>$u_visterInfo['mobile'],
                                    'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
                                    'status'=>'受访人已成功接待您',
                                    'remark'=>"",
                                    'url'=>$url
                            ];
                            $result = $wechatOA->send_message($data);
                            return toJson(['code'=>200,'data'=>$res,'message'=>'成功接待访客']);
                        }
                   }

                    return toJson(['code'=>400,'data'=>['requestTime'=>time()],'message'=>'无权限访问']);
               }
               //
               /*保安扫描二维码-返回访客列表*/
                    // if($code && ($this->user['roleid']==6 || $this->user['roleid'] ==5)){
                    //     $uopenid = $this->redis->get('code_'.$code);
                    //     if(!$uopenid){return toJson(['code'=>400,'message'=>'二维码已过期']);}
                    //     $where = 'openid = "'.$uopenid.'"';
                    //     $userinfo = $this->find('view_user',$where);

                        // $where = ''
                        // $where = 'meeting_code = "'.$code.'"';


                        // $res = $this->find('view_new_app_meeting_info',$where);
                        // if(!$res){return toJson(['message'=>'见面信息不存在','code'=>400]);}
                        // if($res['companyid']!=$this->user['companyid']){return toJson(['message'=>'当前访问信息不在此区域','code'=>400]);}
                       
                        /**区域范围 验证  
                           code......

                        **/
            
                    //     $where = 'vister_uid = '.$userinfo['id'].'and companyid = '.$this->user['companyid'].' and appointment_status = 0 and arrive_status not in(4,5) and app_visittime between '.$today.' and '.$enddaytime;
                    //     $order = 'app_visittime desc';
            
                    //     $data = $this->selectView($this->table_meeting_view, $where, $field = '*', $offset, $length, $order);
                    //     $count = $this->total($this->table_meeting_view, $where, $field = '*');
            
                    //     return toJson(['message'=>'Success_保安访客列表','code'=>200,'data'=>$data,'count'=>$count,'requestTime'=>time()]);
            
                    // }
                /**机器扫码**/
                    if($code && $type == 'dps'){
                        return toJson(['code'=>200,'data'=>['requestTime'=>time(),'scan_log'=>[]],'message'=>'机器扫码']);
                    }

                    return toJson(['code'=>400,'data'=>['requestTime'=>time(),'scan_log'=>[]],'message'=>'无操作权限']);

                break;
            case 'UL':
                /**用户码业务逻辑**/
                /**获取的是该码的该用户信息**/
                $uopenid = $this->redis->get('code_'.$code);
                if(!$uopenid){return toJson(['code'=>400,'message'=>'二维码已过期']);}
                $where = 'openid = "'.$uopenid.'"';
                $userinfo = $this->find('view_user',$where);

                /**扫码记录**/
                $indata = [
                    'icp_sn' => $code,
                    'uid' => $userinfo['id'],
                    'createtime' =>time(),
                    'scan_time' => time(),
                    'type' => 'UL'

                ];
                $this->insert('scan_log',$indata);

                /**业务逻辑**/
                /**-未预约 访客--访客扫了保安二维码**/
                /**闸机无uid 根据后面业务 更改以下代码**/
                //$this->uid =30;

                if($this->uid != $userinfo['id'] && $this->user->roleid!=5 && $this->user->roleid!=6){

                    /**code waite  check appointment**/
                   if($userinfo['roleid']==5 || $userinfo['roleid']==6){

                        $company_info = $this->find('company','id = '.$this->user->companyid);
                        switch ($company_info['type']) {
                            case 2:
                                $where = 'property_id = '.$userinfo['companyid'];
                                # code...
                                break;
                            case 3:
                                $where = 'id = '.$company_info['id'];
                                # code...
                                break;
                            default:
                                $where = 'property_id = '.$userinfo['companyid'];
                                # code...
                                break;
                        }


                        
                        $incompanylist = $this->selectView('view_company',$where);
                    }

                    $redata = [
                        'incompanylist' => $incompanylist?:[],
                    ];

                    $this->redis->set('Vis_addapp_securityuid'.$this->uid,$userinfo['id'],300);

                    return toJson(['code'=>200,'message'=>'','data'=>$redata]);
                }


                /**长期访客  逻辑**/
                //(工厂模式+大厦模式)--保安扫码
                //可废弃 lasttime-2020年10月26日
                $where = 'uid = '.$userinfo['id'].' and companyid ='.$this->user->companyid;
                $long_vister =  Db::table('visiter')->where($where)->find();
                if($long_vister){
                    if(time()>strtotime($long_vister['starttime']) && time()<strtotime($long_vister['endtime'])){
                        return $this->jsonData(ApiErrDesc::SUCCESS[0],ApiErrDesc::SUCCESS[1],$redata);
                    }
                }

                /**企业人员  逻辑**/

                
                
                /**闸机 业务**/
                
                if($type == 'dps'){
                    $data = ['title'=>'进出通知',
                        'openid'=>$uopenid,
                        'name'=>$userinfo['name'],
                        'mobile'=>$userinfo['mobile'],
                        'visittime'=>date('Y-m-d H:i:s',time()),
                        'status'=>'进出通知',
                        'remark'=>"测试",
                        'url'=>''
                    ];
                    $result = $this->wechatOA->send_message($data);
                }

                $scandata = $this->select('view_scan_log', $where = 'uid = '.$userinfo['id'], $field = '*', $offset = 0, $length = 500, $order = 'createtime desc');
                $redata = [
                   'status' => 'isworking',
                   'scanlog' => $scandata
                     ];

                return $this->jsonData(ApiErrDesc::SUCCESS[0],ApiErrDesc::SUCCESS[1],$redata);
                
                break;
            default:
                return $this->jsonData(ApiErrDesc::UNKNOWN_ERR[0],ApiErrDesc::UNKNOWN_ERR[1]);
                break;
        }
        return $this->jsonData(ApiErrDesc::UNKNOWN_ERR[0],ApiErrDesc::UNKNOWN_ERR[1]);
    }
    /**
     * 统一获取code ,生成code 
     * ML-邀请见面类型
     * UL-个人二维码
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-02T15:16:44+0800
     * @LastTime     2020-09-02T15:16:44+0800
     * @return       [type]                   [description]
     */
    public function  makecode(){
        $type = $this->request->param('type');
        switch ($type) {
            case 'ML':
                # code...
                $code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][1]);
                break;
            case 'UL':
                $code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][3]);
                break;
            default:
                return $this->jsonData(ApiErrDesc::UNKNOWN_ERR[0],ApiErrDesc::UNKNOWN_ERR[1]);
                # code...
                break;
        }
        $this->redis->set('code_'.$code,$this->user['openid'],300);
        $data = [
            'code' =>$code,
            'expiretime' => time()+300,
        ];
        return $this->jsonData(ApiErrDesc::SUCCESS[0],ApiErrDesc::SUCCESS[1],$data);
    }


    /**
     * 创建二维码 easywechat
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-27T16:07:50+0800
     * @LastTime     2020-10-27T16:07:50+0800
     * @return       [type]                       [description]
     */
    public function makecode_easy(){
        $app = Factory::officialAccount(Config::get('wx_config'));

    }   


    public function add_qrcode(){
        //1-进入公司 2-离开公司 3-到达指定地点
        $type = trim($this->request->param('type'));
        $companyid = trim($this->request->param('companyid'));
        // $appointment =  trim($this->request->param('companyid'));

        if(empty($type) || empty($companyid)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }


        $codeData = CodeModel::where('type',$type)->where('companyid',$companyid)->find();
        if( $codeData ){
            return toJson(['message'=>'该类型二维码已存在','code'=>200]);
        }

        $count = CodeModel::where('sceneid','neq',0)->count();
         //设定场景值
        $sceneid = $count+1;   

        $code = $this->wechatOA->create_qrcode($sceneid,1);
        
        $codeData = new CodeModel;
        $codeData->companyid = $companyid;
        $codeData->type = $type;
        $codeData->code= $code;
        $codeData->createuid = $this->uid;
        $codeData->createtime = time();
        $codeData->save();
      
        if( $codeData->id > 0 ){
            return toJson(['message'=>'生成二维码成功','codeid'=>$codeData->id,'code'=>'200']);
        }else{
            return toJson(['message'=>'生成二维码出错，请联系客服！','code'=>'400']);
        }      
    }

    public function delete_qrcode(){
        $id = trim($this->request->param('id'));
        if(empty($id)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }

        $codeData = CodeModel::where('id','eq',$id)->find();
        if(empty($codeData)){
            return toJson(['message'=>'二维码信息不存在','code'=>400]);
        }

        $codeData->delete();

        return toJson(['message'=>'删除二维码成功','code'=>200]);
    }


    public function get_qrcode(){
        $id = trim($this->request->param('id'));
        if(empty($id)){
            return toJson(['message'=>'ID不能为空','code'=>400]);
        }

        $codeData = CodeModel::alias('code')
                            ->field('code.*,c.name as cname')
                            ->join('company c','code.companyid=c.id','left')
                            ->where('code.id','eq',$id)
                            ->find();
        if(empty($codeData)){
            return toJson(['message'=>'二维码信息不存在','code'=>'400']);
        }

        return toJson(['data'=>$codeData,'code'=>200]);
    }

    /*插入数据code*/
    public function testcode(){
        $savePath = ROOT_PATH . 'public/qrcode/';
        $webPath = '/qrcode/';
        /*内容*/
        

        $qrLevel = 'H';
        $qrSize = '8';
        /*前缀*/
        $savePrefix = 'qrcode';

        //echo "<img src='".$pic."'>";

        $companyid =  trim($this->request->param('companyid'));
        $deptid  = trim($this->request->param('deptid'));
        $where =  'id = '.$companyid;
        $deptlist = Db::table('company')->where($where)->select();


        for ($i=0; $i <count($deptlist) ; $i++) { 
            $qrData = 'http://devs.zsicp.com/h5/#/pages/qrcode/doorkeeperqrcode?companyid='.$deptlist[$i]['id'].'&door=A';
            
            if($filename = createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix)){
                $pic = $webPath . $filename;
            }
            # code...
            $data = [
                'companyid'=>$deptlist[$i]['id'],
                'code' => $pic,
                'sceneid' =>0,
                'type' =>0,
                'createuid'=>0,
                'createtime'=>time()
            ];
            $res = $this->insert('code', $data);
        }

        return true;
    }
    /*获取二维码*/
    public function codelist(){
        $companyid =  trim($this->request->param('companyid'));
        $deptid  = trim($this->request->param('deptid'));

        $where = 'companyid = '.$companyid; 
        $res = $this->select('code', $where, $field = '*', $offset = 0, $length = 500, $order = null);
        for ($i=0; $i <count($res) ; $i++) { 
            # code...
             echo "<img src='http://devs.zsicp.com/public".$res[$i]['code']."'>";
        }
    
    }
}
